
package application;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import jeopardy.common.Utils;
import jeopardy.common.protocol.useraccount.UserAccountConsts;
import jeopardy.common.protocol.useraccount.UserAccountRequest;
import jeopardy.common.protocol.useraccount.UserAccountUtils;

// import jeopardy.server.ServerConsts;


public class LoginScreenController implements Initializable, ControlledScreen {

	// Variables for reading input from the form
	@FXML
	private Text authMessage;
	@FXML
	private TextField userIDField;
	@FXML
	private TextField passwordField;
	
	public String userName;
	public char[] passWord;
	// static PreGameScreenSession sessionG;

	ScreensController myController;

	/**
	 * Initializes the controller class.
	 */
	@Override
	public void initialize(URL url, ResourceBundle rb) {
		// TODO
	}

	public void setScreenParent(ScreensController screenParent) {
		myController = screenParent;
	}

	/*
	 * @FXML private void goToLoginScreen(ActionEvent event){
	 * myController.setScreen(ScreensFramework.LoginScreenID); }
	 */
	// Process button action
	@FXML
	private void processLoginScreen(ActionEvent event) throws UnknownHostException, IOException, Exception {
		passWord = getPassword();
		userName = getUserName();
		int sockType = 1;
		int authStatus = 0;
		int sockStatus = 0;
		int flightReady = 0;
		String message = "";
		String authMsg = "";
		String statMsg = "";
	
		// System.out.println("User name is: " + userName);
		// System.out.println("Password is: " + passWord);

		if (!UserAccountUtils.validatePasswordString(passWord) || 
				!UserAccountUtils.validateUserString(userName)) {
			authMsg = "Either the User Name or the Password is invalid\n User -" +
			                    "Name should be at least 8 characters long";
			System.out.println(message);

		}
		else {
			System.out.println("LoginScreenController::processLoginScreen - " +
				                   "Authenticating user");
			 sockStatus = LoginScreenLogic.createSocket(sockType);
			
			//Check the socket creation status, if normal, then authenticate user
			if (sockStatus == 0) {
				System.out.println("LoginScreenController::processLoginScreen - " +
				                   "Socket created...sending authentication data");
				
				authStatus = LoginScreenLogic.authenticateUser(userName, passWord);
				
				// Call authenticateUser and check return status - 1 success
				if( authStatus == 1) {
					authMsg = "Authentication Successful";
					
					/*
					System.out.println("LoginScreenController::processLoginScreen -"  + 
					                    "Authentication Successful, loading PreGameScreen");
					*/
					flightReady++;

				}
				// Call authenticateUser and check return status - 0 failure
				if( authStatus == 0) {
					System.out.println("LoginScreenController::processLoginScreen - Authentication failure");
					authMsg = "Authentication failure";
					// myController.setScreen(ScreensFramework.PreGameScreenID);
				}			
			}
			if (sockStatus == 1) {
				/*
				System.out.println("LoginScreenController::processLoginScreen -" +
				                   "Authentication Failure - unable to connect to the server");
				*/
				authMsg = "Failed to communicate with the server";
			}
			
						
			// closet socket since authentication is complete
			LoginScreenLogic.closeSocket(); 
			
			// Attemtp to connect to the server for player statistics
			if(authStatus == 1) {
				sockType = 2;
				sockStatus = PreGameScreenLogic.createSocket(sockType);
				// Socket creation was successful - call methods to query the server
				if (sockStatus == 0) {
					// Call PreGameScreenLogic.main() to start a thread to pull stats from the server
					PreGameScreenLogic.main();
					statMsg = "Retrieving game list & player statistics";
					flightReady++;
				}
				// Socket creation was usuccessful - display message
				if (sockStatus == 1) {
					System.out.println("LoginScreenController::processLoginScreen - failed to" +
						   "Retrieve stats from server");
						   
					statMsg = "Failed to retrieve available games to join";	                   
				}
			}
			
		}
			
		// If flightReady then move to the next screen
		if(flightReady > 1) {
			message = authMsg + statMsg;
			authMessage.setText(message);
			System.out.println("Loading PreGamScreen");
			myController.setScreen(ScreensFramework.PreGameScreenID);

		}
		else {
			message = authMsg + statMsg;
			authMessage.setText(message);
		}
		

	}
	
	// Get user name
	public String getUserName() {
		if (userIDField == null || isEmpty(userIDField.getText())) {
			return "";
		}
		return userIDField.getText();
	}
	

	// Get password
	public char[] getPassword() {
		String password;
		if (passwordField == null || isEmpty(passwordField.getText())) {
			return null;
		}
		else {
			password = passwordField.getText();
			return password.toCharArray();
		}
		
	}

	
	// Check for empty string
	private boolean isEmpty(String s) {
		if((s == null) || s.trim().isEmpty()) {
			return true;		
		}
		else {
			return false;
		}
	}		
}
